package com.zealcomm.ivcscustomer.signature

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.zealcomm.annotations.ChatMessageType
import com.zealcomm.annotations.ChatRoleType
import com.zco.base.ServerCallback
import com.zco.base.annotations.CommandStatus
import com.zco.base.annotations.LinkType
import com.zco.base.entity.*
import com.zealcomm.commonui.base.BaseCallback
import com.zealcomm.commonui.base.BaseFragment
import com.zealcomm.commonui.beans.MessageContent
import com.zco.ivcs.customer.IvcsCustomerCallback
import com.zealcomm.ivcscustomer.R
import com.zealcomm.ivcscustomer.app.IvcsApplication
import com.zealcomm.ivcscustomer.databinding.FragmentSignatureBinding
import com.zealcomm.ivcscustomer.service.MainActivity
import com.zealcomm.utils.ImageUtil
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch

class SignatureFragment : BaseFragment() {

    private var binding: FragmentSignatureBinding? = null
    private val IMAGE_NAME = "signature.png"
    private var signatureCommand: Command<Any>? = null

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        binding = FragmentSignatureBinding.inflate(inflater, container, false)
        binding!!.actionBar.titleName.setText(R.string.signature_on_whiteboard)
        // 关闭硬件加速，否则会获取不到笔迹
        binding!!.svCustomer.setLayerType(View.LAYER_TYPE_SOFTWARE, null)
        setListeners()
        // 发送一个空的笔迹信息来唤起座席端的签名画板
        IvcsApplication.sendHandWritingMessage(null, null)
        return binding!!.root
    }

    override fun initView(view: View?, savedInstanceState: Bundle?) {
    }

    override val layoutId: Int
        protected get() = R.layout.fragment_signature

    private fun setListeners() {
        binding!!.actionBar.back.setOnClickListener {
            removeFragment()
        }
        binding!!.btnCancel.setOnClickListener {
            IvcsApplication.sendHandWritingMessage(null, null)
            binding!!.svCustomer.clearCanvas()
        }
        binding!!.btnSend.setOnClickListener {
            binding!!.svCustomer.evaluateJavascript("javascript:getImage()") {
                IvcsApplication.ivcsCustomer!!.sendFile(
                    ImageUtil.saveBitmap(
                        ImageUtil.base64ToBitmap(it),
                        IMAGE_NAME
                    ), object : ServerCallback<UploadFileRes>() {

                        override fun onSuccess(t: UploadFileRes?) {
                            super.onSuccess(t)
                            val linkInfo = LinkInfo(LinkType.LINK_PIC , t?.data?.originalname , t?.data?.url)
                            signatureCommand?.status = CommandStatus.DONE
                            signatureCommand?.data = linkInfo
                            (holdingActivity as MainActivity).addChatMessage(MessageContent(ChatRoleType.CUSTOMER ,
                                SessionMessage(ChatMessageType.COMMAND , signatureCommand)))
                            IvcsApplication.ivcsCustomer!!.sendPeerResponse(
                                null,
                                signatureCommand,
                                object : IvcsCustomerCallback {
                                    override fun onSuccess() {
                                        showToast(getString(R.string.commit_sign_success))
                                        GlobalScope.launch(Dispatchers.Main) {
                                            // 这个 Toast 框架在 activity 调整的时候会改变大小，所以这里延迟下
                                            Thread.sleep(200)
                                            removeFragment()
                                        }
                                    }

                                    override fun onFailed(code: Int, error: String?) {
                                        showToast(getString(R.string.commit_sign_failed))
                                    }

                                })
//                            val info = SystemTraceBean.Info()
//                            info.url = data?.url
//                            info.filename = data?.name
//                            SystemTraceUtil.addTrace(SystemTraceType.SEND_HAND_SIGN_LINK, info)
                        }

                        override fun onFailure(generalErrorBean: GeneralErrorBean?) {
                            super.onFailure(generalErrorBean)
                            showToast(getString(R.string.commit_sign_failed))
                        }
                    })
            }
        }
        binding!!.svCustomer.setOnCanvasUpdateListener {
            IvcsApplication.sendHandWritingMessage(null, it)
        }
    }

    companion object {
        fun getInstance(callback: BaseCallback?): SignatureFragment {
            val fragment = SignatureFragment()
            fragment.setBaseCallback(callback)
            return fragment
        }

        fun getInstance(
            signatureCommand: Command<Any>?,
            callback: BaseCallback
        ): SignatureFragment {
            val fragment = SignatureFragment()
            fragment.setBaseCallback(callback)
            fragment.signatureCommand = signatureCommand
            return fragment
        }
    }
}